#coding=utf-8

# Author: Azhen,Nemo
# Email: azhenfeixue@gamil.com, nemo.zhp@gmail.com

# Create your views here.
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.utils import simplejson
from django.db.models import permalink
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context, RequestContext
from meet001.meetup.forms import GroupCreateForm, RegisterForm
from meet001.meetup.forms import GroupSearchForm
from meet001.meetup.models import  Group, User, Membership
from meet001.meetup.location import location_code, city_code, \
district_code,city_district, code_to_city, code_to_district
from meet001.commentboard.models import CommentBoard
import urllib
import datetime

import uuid
from util import get_thumbnail, async_send_mail
try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO


ERRMSG_CREATOR_NOT_EXIST = '''创建者还未注册，花一分钟注册一个吧！'''

GROUP_UPDATE_EMAIL_SUBJECT = u'群组信息更新啦'
GROUP_UPDATE_EMAIL_FROM_ADDRESS = 'pengtouba@gmail.com'

# handle /group/create/
# last changed by nemo.09-06-18

def create(request):
  anonymous = True
  if not request.user.is_anonymous():
    anonymous = False
  if request.method == "POST":
    form = GroupCreateForm(request.POST, request.FILES)
    if form.is_valid():
      id = form.save(request.user.username)
      add_member(id, request.user.id)
      return HttpResponseRedirect('/group/' + str(id) + '/')
    
    # here should show the error message!
    return render_to_response('meetup_group_create.html',   
       {'form': form, 'anonymous':anonymous, 
         'city_district':city_district,
        'failed': True},
       context_instance=RequestContext(request))
  else:
    form = GroupCreateForm()
    return render_to_response('meetup_group_create.html',
        {'form': form, 'anonymous':anonymous, 
         'city_district':city_district,
         'failed': False},
        context_instance=RequestContext(request))

# handler /group/search/
def search(request, group_name="", city="", district=""):
  if request.method == "POST":
    search_result = None
    form = GroupSearchForm(request.POST)
    if form.is_valid():
      matched_groups = form.search()
      if matched_groups.count() > 0:
        search_result = matched_groups
        #return HttpResponseRedirect("/group/%s" %matched_groups[0].id)
    # If search failed.
    return render_to_response('meetup_group_search_result.html',
        {'form': form,
          'failed': True,
          'search_result':search_result,
          'city_district':city_district},
        context_instance=RequestContext(request))
  else:
    form = GroupSearchForm({'name':group_name})
    total_group_num = Group.objects.all().count()
    return render_to_response('meetup_group_search.html',
        {'form': form, 'total_group_num': total_group_num,
          'city_district':city_district,
          'failed': False},
        context_instance=RequestContext(request))


#added by zhangpeng handle group_details
def details(request, group_id=""):
  """display group page, and show special link for pages"""
  
  if request.method == 'POST':
    group = Group.objects.get(pk=group_id)
    old_name = group.name
    upd_dict=update(request, group_id)
    if 'notify_others' in request.POST and request.POST['notify_others']==u'true':
      url = request.build_absolute_uri(get_group_detail_url(group_id))
      send_group_update_notification(Group.objects.get(pk=group_id), old_name,url)
    return HttpResponse(simplejson.dumps(upd_dict), mimetype='application/javascript')
  joined = False
  anonymous = True
  if not request.user.is_anonymous():
    anonymous = False
  if group_id:
    #find whether the group exist
    group = None
    try:
      group = Group.objects.get(id=group_id)
    except:
      pass
    if group:
      #if exists, display it
      creator = False
      if group.creator == request.user:
        creator = True
      #to see whether current user have already joined the group
      if request.user in group.users.all():
        joined = True

      # Get the next meeVtup.
      meetups = list(group.meetup_set.order_by('-time_from'))
      next_meetup = None
      upcoming_meetup = []
      past_meetup = []
      now = datetime.datetime.now()
      for meetup in meetups:
        if meetup.time_from> now:
          if next_meetup:
            upcoming_meetup.append(next_meetup)
          next_meetup = meetup
        else:
          past_meetup.append(meetup)
      upcoming_meetup.reverse()

      return render_to_response('meetup_group_details.html', 
          {'anonymous':anonymous,'joined':joined, 'user':request.user,
            'creator': creator,
            'next_meetup': next_meetup,
            'upcoming_meetups': upcoming_meetup,
            'past_meetups': past_meetup,
            'city_district': city_district,
            'default_city':code_to_city[group.city],
            'default_district':code_to_district[group.district],
            'group':group},
          context_instance=RequestContext(request))
    else:
      #if not exist, show edit page
      return HttpResponseRedirect('/groups/create/')
  else:
    #show group search lists, to be defined
    return HttpResponseRedirect('/groups/search/')

# handle /thanks/
def thanks(request):
  return render_to_response('meetup_group_thanks.html', {}, context_instance=RequestContext(request))

#handle /update/
def update(request, group_id):
  #dosomething

  upd_dict={}
  target_group = Group.objects.get(id=group_id)
  target_group.description = request.POST[u'description']
  if eval(request.POST['member_limit']) <= 9999999:
    target_group.member_limit=request.POST['member_limit']
  target_group.name = request.POST[u'groupname']
  target_group.title = request.POST[u'title']
  target_group.location = location_code[(request.POST[u'city'],
        request.POST[u'district'])] 
  target_group.city = city_code[request.POST[u'city']]
  target_group.district =district_code[request.POST['district']]
  upd_dict['name'] = target_group.name
  upd_dict['title'] = target_group.title
  upd_dict['member_limit'] = target_group.member_limit
  upd_dict['description'] = target_group.description
  upd_dict['city']=request.POST['city']
  upd_dict['district']=request.POST['district']
  
  if request.FILES.has_key('picture'):
      picture_name = uuid.uuid4().hex + request.FILES['picture'].name
      target_group.picture = 'photos\\group_pic\\' + picture_name
      image = get_thumbnail(request.FILES['picture'], (300, 210))
      image.save(target_group.picture.path)
      upd_dict['picture_url'] = picture_name
  target_group.save()
  return upd_dict
  
# handle /join/
def join(request, usertype=0):
  if request.method == "POST":
    group = add_member(request.POST['group_id'], request.POST['user_id'], usertype)
    #after join, go to the group_details page
    return HttpResponseRedirect('/group/' + request.POST['group_id'] + '/')
  #if request not post method, we should return a group list
  return HttpResponseRedirect('/groups/search/')
 
  
#join a memeber into a group
#normal user type is 0
#admin type is 1, when the creation of group happens.
def add_member(group_id, user_id, usertype=0):
  new_user = User.objects.get(id=user_id)
  new_group = Group.objects.get(id=group_id)
  
  #to see whether the memebership is already exist
  if Membership.objects.filter(user=new_user, group=new_group).count() > 0 :
    return new_group
  new_membership = Membership()
  new_membership.user = User.objects.get(id=user_id)
  new_membership.group = Group.objects.get(id=group_id)
  new_membership.usertype = usertype
  new_membership.save()
  return new_membership.group

def create_plus_join(groupDict, user):
  
  #to see whether the group is already exist
  
  groups = Group.objects.filter(creator=user, name=groupDict['groupname'])
  if groups.count() > 0:
    return groups[0]
    
  new_group = Group()
  new_group.description = groupDict['description']
  new_group.creator = user
  new_group.title = groupDict['title']
  new_group.name = groupDict['groupname']
  new_group.city = city_code[form_data['city']]
  new_group.district = district_code[form_data['district']]
  new_group.location = location_code[(groupDict['city'],
    groupDict['district'])] 
  if form_data['picture'] is not None:
    new_group.picture = 'photos\\group_pic\\' + uuid.uuid4().hex + groupDict['picture'].name
    image = get_thumbnail(groupDict['picture'], (300, 210))
    image.save(new_group.picture.path)
  
  #added member_limit and found_date
  new_group.member_limit = groupDict['member_limit']
  new_group.comment_board = CommentBoard.create_board()

  new_group.save()
  #add the creator as admin for the group
  add_member(new_group.id, user.id, 1)
  return new_group


def send_group_update_notification(group, old_name, url):
  content = u"“"+group.name+u"”小组刚刚更新了群组信息。\n"
  if not old_name == group.name:
    content += "原来的名称为："+old_name + "现在的名称为："+group.name + "\n"
  else:
    content +="小组“"+group.name + "”的信息：\n"
  content +="新的小组标题是——"+group.title + "\n"
  content += "新的小组介绍是：\n"+group.description + "\n 快来看看吧：\n"+url
  #decide which user should receive this notice
  for group_user in group.users.all():
    async_send_mail("您参加的“"+group.name+"”小组"+ GROUP_UPDATE_EMAIL_SUBJECT, content, GROUP_UPDATE_EMAIL_FROM_ADDRESS, [group_user.email])

@permalink
def get_group_detail_url(group_id):
  return ('meet001.meetup.group_views.details', [group_id])